<template>
  <div class="app-container">

    <div class="filter-container">
      <el-button class="filter-item" type="primary" icon="el-icon-refresh" @click="getList()">刷新菜单</el-button>
      <!--      <el-button class="filter-item" type="primary" icon="el-icon-refresh" @click="changeExpandState()">展开|折叠</el-button>-->
      <el-button class="filter-item" type="primary" icon="el-icon-plus" @click="handleCreate(null)">新增一级菜单</el-button>
    </div>

    <el-table
      :key="tableKey"
      ref="menuTree"
      v-loading="listLoading"
      :data="treeTableDataList"
      border
      fit
      highlight-current-row
      :tree-props="treeOption"
      row-key="id"
      height="75vh"
      :default-expand-all="expandAll"
    >
      <el-table-column
        v-for="column in columns"
        :key="column.prop"
        :prop="column.prop"
        :label="column.label"
        :width="column.width"
        :align="column.align?column.align:'center'"
        :min-width="column.minWidth"
        :sortable="column.sortable"
        :fixed="column.fixed"
        :type="column.type"
        :formatter="column.formatter"
      >
        <template slot-scope="scope">
          <!-- 图片 -->
          <img
            v-if="column.imgFlag===true"
            :src="CMBASE.baseUploadAction+scope.row[column.prop]"
          >
          <!-- 文字格式化 -->
          <span v-else-if="column.formatter">
            {{ column.formatter(scope.row) }}
          </span>
          <!-- tag标签 -->
          <span v-else-if="column.tagFlag===true">
            <span v-for="item in column.tagFormatter" :key="item.value">
              <el-tag v-if="item.value===scope.row[column.prop]" :type="item.type">{{ item.text }}</el-tag>
            </span>
          </span>
          <!-- 开关按钮 -->
          <el-switch
            v-else-if="column.switchFlag===true"
            v-model="scope.row[column.prop]"
            :active-value="1"
            :inactive-value="0"
            disabled
          />
          <!-- 普通文本数据 -->
          <span v-else class="ellipsis">{{ scope.row[column.prop] }}</span>
        </template>
      </el-table-column>

      <el-table-column :label="'操作'" align="center" width="250" fixed="right" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="primary" @click="handleCreate(scope.row.id)">新增子级</el-button>
          <el-button type="published" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 新增修改界面 -->
    <el-dialog :title="operation?'新增':'编辑'" :visible.sync="dialogFormVisible" :close-on-click-modal="false" width="50%">
      <el-form
        ref="dataForm"
        :model="dataForm"
        :rules="dataFormRules"
        label-width="120px"
        size="small"
        style="text-align:left;"
        @keyup.enter.native="saveFormData()"
      >
        <el-form-item label="菜单类型" prop="type">
          <el-radio-group v-model="dataForm.type">
            <el-radio v-for="(type, index) in menuTypeList" :key="index" :label="index">{{ type }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="menuTypeList[dataForm.type] + '名称'" prop="name">
          <el-input v-model="dataForm.name" :placeholder="menuTypeList[dataForm.type] + '名称'" />
        </el-form-item>
        <el-form-item label="菜单编码" prop="code">
          <el-input v-model="dataForm.code" placeholder="菜单编码" />
        </el-form-item>
        <!--        <el-form-item v-if="dataForm.type === 1" label="菜单路由(html)" prop="url">-->
        <!--          <el-input v-model="dataForm.pageurl" placeholder="菜单路由(html)" />-->
        <!--        </el-form-item>-->
        <el-form-item v-if="dataForm.type === 0 || dataForm.type === 1" label="菜单路由(VUE)" prop="url">
          <el-input v-model="dataForm.remark" placeholder="菜单路由(VUE)" />
        </el-form-item>
        <el-form-item v-if="dataForm.type === 2 " label="授权标识" prop="perms">
          <el-input v-model="dataForm.code" placeholder="如: sys:user:add, sys:user:edit, sys:user:delete" />
        </el-form-item>
        <el-form-item v-if="dataForm.type !== 2" label="排序编号" prop="orderNo">
          <el-input-number v-model="dataForm.orderNo" :min="0" :max="1000" />
        </el-form-item>
        <el-form-item v-if="dataForm.type !== 2" label="菜单图标" prop="icon">
          <el-row>
            <el-col :span="22">
              <el-input v-model="dataForm.icon" v-popover:iconListPopover :readonly="false" placeholder="菜单图标名称（如：fa fa-home fa-lg）" class="icon-list__input" />
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="是否展示" prop="showFlag">
          <el-switch v-model="dataForm.showFlag" :active-value="1" :inactive-value="0" label="是否展示" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog()">取消</el-button>
        <el-button :loading="editLoading" size="small" type="primary" @click="saveFormData()">确定</el-button>
      </span>
    </el-dialog>

  </div>

</template>

<script>
/**
  Auth: chenyue1993
  Created: 2019/11/14-14:54
*/
import { getMenuTreeList, saveMenuInfo, deleteMenu } from '../../../api/modules/cm-system'
export default {
  name: 'SystemMenu',
  data() {
    return {
      treeOption: {
        children: 'children',
        hasChildren: 'hasChildren'
      },
      listLoading: false,
      tableKey: 0,
      expandAll: false, // 默认不展开所有节点
      columns: [
        { label: '资源名称', prop: 'name', align: 'center', minWidth: 120 },
        { label: '资源类型', prop: 'type', align: 'center', tagFlag: true, minWidth: 120,
          tagFormatter: [
            { text: '导航目录', value: 0, type: '' },
            { text: '跳转菜单', value: 1, type: 'success' },
            { text: '页面按钮', value: 2, type: 'danger' }
          ]
        },
        { label: '资源编码', prop: 'code', align: 'center', minWidth: 120 },
        { label: '跳转地址', prop: 'remark', align: 'left', minWidth: 120 },
        // { text: '跳转地址', value: 'pageurl', align: 'left' },
        { label: '图标', prop: 'icon', align: 'center', minWidth: 120, iconFlag: true },
        { label: '是否展示', prop: 'showFlag', align: 'center', minWidth: 120, switchFlag: true },
        { label: '排序', prop: 'orderNo', align: 'center', minWidth: 120 }
      ],
      treeTableDataList: [],
      operation: true, // 默认标记新增
      dialogFormVisible: false,
      editLoading: false,
      menuTypeList: ['目录', '菜单', '按钮'],
      dataForm: {},
      dataFormRules: {
        name: [{ required: true, message: '菜单名称不能为空', trigger: 'blur' }],
        // code: [{ required: true, message: '请输入资源编码', trigger: 'blur' }],
        type: [{ required: true, message: '请选择资源类型', trigger: 'blur' }],
        orderNo: [{ required: true, message: '请输入排序号码', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 改变展开收缩
    changeExpandState() {
      this.expandAll = !this.expandAll
      // console.log(this.$refs.menuTree)
        // for (let i = 0; i < this.$refs.menuTree._getAllNodes().length; i++) {
      //   this.$refs.menuTree._getAllNodes()[i].expanded = this.expandAll
      // }
    },
    // 获取数据
    async getList() {
      this.listLoading = true
      // 【API请求】---- 获取资源菜单树数据
      const res = await getMenuTreeList(this.listQuery)
      this.treeTableDataList = res.result
        this.listLoading = false
    },

    // 【按钮点击】--- 弹出新增表单
    handleCreate(pid) {
      this.operation = true
      this.initDataForm()
      if (pid) {
        this.dataForm.pid = pid
      }
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
        this.editLoading = false
      })
    },
    // 【按钮点击】--- 弹出编辑表单
    handleUpdate(row) {
      this.operation = false
      this.dataForm = {
        id: row.id,
        pid: row.pid,
        name: row.name,
        code: row.code,
        pageurl: row.pageurl,
        remark: row.remark,
        type: row.type,
        showFlag: row.showFlag,
        orderNo: row.orderNo,
        icon: row.icon
      },

      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
        this.editLoading = false
      })
    },
    // 保存表单数据
    saveFormData() {
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          return false
        }
        this.editLoading = true
        // 【API请求】----保存表单数据
        saveMenuInfo(this.dataForm).then(() => {
          this.editLoading = false// 关闭loading框
          this.dialogFormVisible = false// 关闭表单页面
          this.getList()// 重新获取表格数据
          this.initDataForm()
          this.$notify({ title: '成功', message: '保存成功', type: 'success', duration: 2000 })
        })
      })
    },
    // 【按钮点击】---删除行
    handleDelete(row) {
      if (row.children.length > 0) {
        this.$message({ message: '该菜单下存在子级菜单，不可删除', type: 'error' })
        return
      }
      this.$confirm('确认删除该记录吗？', '提示', {}).then(() => {
        // 【API请求】---- 删除一行数据
        deleteMenu({ ids: row.id }).then(() => {
          this.$message({ message: '操作成功', type: 'success' })
          this.getList()
        })
      }).catch(() => {

      })
    },
    // 关闭表单弹出框
    closeDialog() {
      this.initDataForm()
      this.dialogFormVisible = false
    },
    // 初始化表单数据
    initDataForm() {
      this.dataForm = {
        id: '',
        pid: '',
        name: '',
        code: '',
        pageurl: '',
        type: 1,
        showFlag: 1,
        icon: '',
        orderNo: 0
      }
    }

  }

}
</script>
